package com.wayne.servlet;

import cn.hutool.json.JSONUtil;
import com.wayne.factory.ProxyFactory;
import com.wayne.service.TransferService;
import com.wayne.vo.Result;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {
  private TransferService transferService ;
  @Override
  public void init() {
    WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ProxyFactory proxyFactory = (ProxyFactory) webApplicationContext.getBean("proxyFactory");
    transferService = (TransferService) proxyFactory.getJdkProxy(webApplicationContext.getBean("transferService"));
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 设置请求体的字符编码
    req.setCharacterEncoding("UTF-8");
    String fromCardNo = req.getParameter("fromCardNo");
    String toCardNo = req.getParameter("toCardNo");
    String moneyStr = req.getParameter("money");
    int money = Integer.parseInt(moneyStr);
    Result result = new Result();
    try {
      transferService.transfer(fromCardNo, toCardNo, money);
      result.setStatus("200");
    } catch (Exception e) {
      e.printStackTrace();
      result.setStatus("201");
      result.setMessage(e.toString());
    }
    // 响应
    resp.setContentType("application/json;charset=utf-8");
    resp.getWriter().println(JSONUtil.toJsonStr(result));
  }
}
